<template>
  <div class="app-container">
    <list-page-container>

      <template slot="query">
        <el-form :model="queryParams" :rules="queryRules" ref="queryForm" size="small" :inline="true"
                 label-width="80px">
          <el-form-item label="隐患类别" prop="typeSerial">
            <el-cascader
                :props="{value:'typeSerial',label:'typeName'}"
                v-model="queryParams.typeSerial"
                :options="options"></el-cascader>
          </el-form-item>
          <el-form-item label="关键字" prop="keyword">
            <el-input
                v-model="queryParams.keyword"
                placeholder="请输入关键字"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </template>

      <template slot="table">
        <el-table class="single-choice" v-loading="loading" @select="handleSelectionChange" :data="dataList" ref="defectTable">
          <el-table-column v-if="checkDefect" type="selection" width="55" align="center"/>
          <el-table-column label="大类名称" align="center" prop="parentTypeName"/>
          <el-table-column label="子类名称" align="center" prop="typeSerialName"/>
          <el-table-column label="项目" align="center" prop="itemName"/>
          <el-table-column label="项目内容" align="center" prop="itemContent"/>
          <el-table-column label="标准分值" align="center" prop="itemScore"/>
          <!--          <el-table-column label="类别代码" align="center" :show-overflow-tooltip="true">-->
          <!--            <template slot-scope="scope">-->
          <!--              <router-link :to="{path:'/system/defectTypeInfo', query:{parentTypeCode:scope.row.id}}" class="link-type">-->
          <!--                <span>{{ scope.row.typeCode }}</span>-->
          <!--              </router-link>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column width="200" v-if="!checkDefect" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="goInfoPage(scope.row)"
              >详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <template slot="pageDisplay">
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
      </template>
    </list-page-container>
  </div>
</template>

<script>
import {
  getDefectTypeInfoById,
  getDefectTypeInfoByItemSerial,
  getDefectTypeList,
  getDefectTypeTree,
} from "@/api/system/defectType";
import {isArr} from "@/utils/arrayUtil";

export default {
  name: "defectType_list",
  props: {
    checkDefect: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Object, Number]
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      currentTableDefect: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeSerial: null,
        keyword: null,
      },
      queryRules: {
        typeSerial: [
          {required: true, message: "隐患类别不能为空", trigger: "blur"}
        ]
      },
      options: [],
      dataList: [],
      total: 0,
      loading: false,
    }
  },
  watch: {
    value: {
      async handler() {
        let {value} = this
        if (value == null || value === '') return
        if (typeof value == 'number' || typeof value == 'string') {
          let defect = await this.getCurrentTableDefect()
          this.currentTableDefect = defect.data
          this.getList()
          this.submitData()
        }
      },
      deep: true,
      immediate: true
    },
    currentTableDefect(val) {
      if (val?.id != this.currentTableDefect?.id) {
        this.submitData()
      }
    },
  },
  methods: {
    submitData() {
      let {currentTableDefect} = this
      if (currentTableDefect == null) return;
      this.$emit('change', currentTableDefect)
    },
    handleSelectionChange(val, currentRow) {
      this.$refs.defectTable.clearSelection();
      this.$refs.defectTable.toggleRowSelection(currentRow);
      this.currentTableDefect = _.cloneDeep(currentRow)
      this.submitData()
    },
    getCurrentTableDefect() {
      let {value} = this
      return new Promise(async (resolve, reject) => {
        if (value == null || value === '') {
          resolve(null)
          return
        }
        let defect = await getDefectTypeInfoByItemSerial(value);
        resolve(_.cloneDeep(defect))
      })
    },
    goInfoPage(row) {
      this.$router.push({path: '/business/defectTypeInfo', query: {defectTypeId: row.id}})
    },

    /** 导出按钮操作 */
    handleExport() {

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getList() {
      let owner = this
      let {currentTableDefect} = this
      let {queryParams: {typeSerial, keyword, pageSize, pageNum}} = owner
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          const queryParams = {typeSerial: typeSerial[1], keyword, pageSize, pageNum}
          owner.loading = true;
          getDefectTypeList(queryParams).then(response => {
                owner.dataList = response.rows;
                let cItem = response.rows.find(item => item.id == currentTableDefect.id);

                if (currentTableDefect?.id != null && cItem) {
                  owner.$nextTick(() => {
                    owner.handleSelectionChange([cItem], cItem)
                  });
                }
                owner.total = response.total;
                owner.loading = false;
              }
          );
        }
      });
    },
    getTreeData() {
      this.startLoading('正在加载....')
      let owner = this
      return new Promise((resolve, reject) => {
        getDefectTypeTree().then(res => {
          owner.options = owner.changeOptions(res.data)
          resolve(owner.options)
        }).finally(() => {
          owner.endLoading()
        })
      })
    },
    changeOptions(options) {
      const newOptions = [];
      options.forEach(item => {
        let {typeSerial, typeName, children} = item;
        const newItem = isArr(children) ? {typeSerial, typeName, children} : {typeSerial, typeName};
        if (isArr(newItem.children)) {
          // 递归处理子节点
          newItem.children = this.changeOptions(newItem.children);
        }
        newOptions.push(newItem);
      });
      return newOptions;
    },
    findFirstLeafNode(tree, res = []) {
      tree.forEach((item, index) => {
        let {typeSerial, typeName, children} = item;
        if (index == 0) {
          // 递归处理子节点
          res.push(typeSerial);
          if (isArr(children)) {
            this.findFirstLeafNode(children, res);
          }
        }
      });
      return res; // 没有找到叶子节点时返回空数组
    }
  },

  created() {
    let owner = this
    this.getTreeData().then(res => {
      owner.$nextTick(() => {
        if (isArr(res)) {
          let baseTypeSerial = owner.findFirstLeafNode(res)
          if (isArr(baseTypeSerial)) {
            owner.queryParams.typeSerial = baseTypeSerial
            owner.getList()
          }
        }
      })
    });
  },
}
</script>

<style scoped>

</style>
